package com.gilight.base.aspect;

import com.alibaba.fastjson.JSONObject;
import com.gilight.base.aspect.annotation.Auth;
import com.gilight.base.base.RepStatusCode;
import com.gilight.base.base.exception.AppServiceException;
import com.gilight.base.base.exception.ServiceException;
import com.gilight.base.common.Const;
import com.gilight.base.dto.uni.UserDTO;
import com.gilight.base.properties.UnimallSystemProperties;
import com.gilight.base.util.DbSearchBuilder;
import com.gilight.base.util.IPUtils;
import com.gilight.base.util.SessionUtil;
import org.lionsoul.ip2region.DbSearcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.WebRequestInterceptor;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Component
public class RequestInterceptor extends HandlerInterceptorAdapter {
    private final Logger logger = LoggerFactory.getLogger(RequestInterceptor.class);

    @Autowired
    private StringRedisTemplate userRedisTemplate;
    @Autowired
    private UnimallSystemProperties unimallSystemProperties;
    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 20,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Date date = new Date();
        logger.info("request请求地址path[{}] uri[{}]", request.getServletPath(), request.getRequestURI());
        try{
            String ip = IPUtils.getIpAddr(request);
            String reginGeo  = IPUtils.getCityInfo(ip);
            request.setAttribute("currentIp",ip);
            request.setAttribute("currentGeo",reginGeo);
        }catch (Exception e){
            logger.info("解析地址失败");
        }

        Auth auth = null;
        if(handler instanceof HandlerMethod) {
            HandlerMethod h = (HandlerMethod)handler;
            auth = h.getMethodAnnotation(Auth.class);
        }
        if(auth != null){
            String accessToken = request.getHeader(Const.USER_ACCESS_TOKEN);
            if (!StringUtils.isEmpty(accessToken)) {
                String userJson = userRedisTemplate.opsForValue().get(Const.USER_REDIS_PREFIX + accessToken);
                if (!StringUtils.isEmpty(userJson)) {
                    UserDTO userDTO = JSONObject.parseObject(userJson, UserDTO.class);
                    request.setAttribute("user",userDTO);
                    SessionUtil.setUser(userDTO);
                    userRedisTemplate.expire(Const.USER_REDIS_PREFIX + accessToken, unimallSystemProperties.getUserSessionPeriod(), TimeUnit.MINUTES);
                }else{ //登陆过期
                     throw new AppServiceException("登陆超时",403, RepStatusCode.NO_AUTH_ERROR);
                }
            } else {
                throw new AppServiceException("没有权限", 403,RepStatusCode.NO_AUTH_ERROR);
            }
        }
        return true;
    }
}




